'use client';

import React, { useState } from 'react';
import { Modal, Form, Input, Button } from 'antd';
import { MobileOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useMessage } from '@/hooks/useMessage';
import { useAuth } from '../../components/AuthProvider';

interface BindPhoneModalProps {
  userInfo: any;
  onClose: () => void;
  onSuccess: () => void;
}

interface BindPhoneForm {
  phone: string;
  code: string;
}

const BindPhoneModal: React.FC<BindPhoneModalProps> = ({
  userInfo,
  onClose,
  onSuccess
}) => {
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const message = useMessage();
  const [form] = Form.useForm();
  const { bindPhone } = useAuth();

  // 发送验证码
  const sendSmsCode = async (phone: string) => {
    if (countdown > 0) return;
    
    try {
      // TODO: 调用发送短信验证码API
      console.log('发送验证码到:', phone);
      message.success('验证码已发送');
      
      // 开始倒计时
      let count = 60;
      setCountdown(count);
      const timer = setInterval(() => {
        count -= 1;
        setCountdown(count);
        if (count <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } catch (error) {
      message.error('验证码发送失败');
    }
  };

  // 绑定手机号
  const handleBindPhone = async (values: BindPhoneForm) => {
    setLoading(true);
    try {
      const success = await bindPhone(values.phone, values.code, userInfo.openid);
      
      if (success) {
        message.success('绑定成功，登录中...');
        setTimeout(() => {
          onSuccess();
        }, 1000);
      } else {
        message.error('绑定失败，请重试');
      }
    } catch (error) {
      console.error('绑定失败:', error);
      message.error('绑定失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleGetCode = () => {
    const phone = form.getFieldValue('phone');
    if (phone && /^1[3-9]\d{9}$/.test(phone)) {
      sendSmsCode(phone);
    } else {
      message.error('请先输入正确的手机号');
    }
  };

  return (
    <Modal
      open={true}
      onCancel={onClose}
      footer={null}
      width={400}
      centered
      closable={false}
    >
      <div className="p-4">
        <div className="flex items-center mb-6">
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={onClose}
            className="mr-2"
          />
          <h2 className="text-lg font-medium mb-0">首次登录请绑定手机号</h2>
        </div>

        <Form
          form={form}
          onFinish={handleBindPhone}
          layout="vertical"
        >
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input
              placeholder="请输入手机号"
              size="large"
              prefix={<MobileOutlined />}
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <div className="flex gap-2">
              <Input
                placeholder="请输入验证码"
                size="large"
                className="flex-1"
              />
              <Button
                size="large"
                disabled={countdown > 0}
                onClick={handleGetCode}
                style={{ color: '#52c41a', borderColor: '#52c41a' }}
              >
                {countdown > 0 ? `${countdown}s` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
              className="w-full"
              style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
            >
              确定
            </Button>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default BindPhoneModal; 